<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.revoke" style="width: 200px" class="filter-item" placeholder="请选择状态">
        <el-option :label="'全部'" :value="''" />
        <el-option :label="'发布中'" :value="false" />
        <el-option :label="'已撤销'" :value="true" />
      </el-select>
      <el-input v-model="listQuery.title" clearable style="width: 200px" class="filter-item" placeholder="标题"/>
      <el-input v-model="listQuery.content" clearable style="width: 200px" class="filter-item" placeholder="内容"/>
      <el-button v-permission="['notify:list']" clearable class="filter-item" type="primary" icon="el-icon-search" @click="search">查找</el-button>
      <el-button v-permission="['notify:add']" class="filter-item" type="primary" icon="el-icon-edit" @click="openNotify(true,null)">添加</el-button>
    </div>
    <el-table v-loading="listLoading" :data="list" size="small" element-loading-text="正在查询中..." border fit highlight-current-row>
      <el-table-column align="center" label="标题" prop="title"/>
      <el-table-column align="center" label="发布时间" prop="createDate" width="150"/>
      <el-table-column align="center" label="撤销时间" prop="revokeDate" width="150"/>
      <el-table-column align="center" label="发布状态" width="200">
        <template slot-scope="scope">
          <el-switch v-permission="['notify:editStatus']" v-model="scope.row.revoke" :active-value="false" :inactive-value="true" active-color="#13ce66" @change="changeRevoke(scope.row.id,$event)"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="400">
        <template slot-scope="scope">
          <el-button v-permission="['notify:detail']" type="primary" size="mini" @click="openNotify(false,scope.row)">编辑</el-button>
          <el-button v-permission="['notify:delete']" type="danger" size="mini" @click="remove(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize" @pagination="initList"/>

    <el-dialog :close-on-click-modal="false" :visible.sync="notifyDialogVisible" :title="isAdd?'发布系统通知':'编辑系统通知'" @close="destroy">
      <el-form ref="notifyForm" :rules="notifyRules" :model="notifyForm" label-width="80px">
        <el-form-item label="标题" label-width="100" prop="title">
          <el-input v-model="notifyForm.title" placeholder="请输入通知标题" maxlength="200"/>
        </el-form-item>
        <el-form-item label="内容" label-width="100" prop="content">
          <editor ref="editor" :init="editorInit" v-model="notifyForm.content"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="destroy">取 消</el-button>
        <el-button v-permission="['notify:add']" v-if="isAdd" type="primary" @click="addNotify">确 定</el-button>
        <el-button v-permission="['notify:edit']" v-else type="primary" @click="editNotify">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
</style>

<script>
import { NotifyService } from '@/api/MessageService'
import Pagination from '@/components/Pagination'
import Notify from '@/utils/notify'
import { CommonService } from '@/api/CommonService'
import Editor from '@tinymce/tinymce-vue'

export default {
  name: 'Notify',
  components: { Pagination, Editor },
  data() {
    return {
      notifyDialogVisible: false,
      notifyForm: { id: 0, title: undefined, content: undefined },
      notifyRules: {
        title: [{ required: true, message: '请输入通知标题!', trigger: 'blur' }],
        content: [{ required: true, message: '请输入通知内容!', trigger: 'blur' }]
      },
      list: [],
      total: 0,
      listLoading: true,
      isAdd: true,
      listQuery: { pageNo: 1, pageSize: 20, revoke: undefined, title: undefined, content: undefined },
      editorInit: {
        language: 'zh_CN',
        convert_urls: false, height: 300,
        plugins: ['advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'],
        toolbar: ['searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample', 'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          CommonService.uploadFile(formData).then(res => {
            success(res.url)
          }).catch((e) => {
            console.log(e)
            failure('上传失败，请重新上传')
          })
        }
      }
    }
  },
  created() {
    this.initList()
  },
  methods: {
    initList() {
      this.listLoading = true
      NotifyService.listNotify(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.totalCount
        this.listLoading = false
      })
    },
    search() {
      this.listQuery.pageNo = 1
      this.initList()
    },
    remove(row) {
      this.$confirm('您确认要删除该通知吗?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        NotifyService.delNotify(row.id).then(() => {
          Notify.success(this, '删除成功!')
          this.initList()
        })
      }).catch(() => {
        return false
      })
    },
    changeRevoke(notifyId, revoke) {
      NotifyService.editNotifyRevoke(notifyId, revoke).then(() => {
        this.initList()
      })
    },
    openNotify(isAdd, row) {
      this.notifyDialogVisible = true
      this.isAdd = isAdd
      if (!isAdd) {
        this.notifyForm = Object.assign({}, row)
      }
    },
    destroy() {
      this.notifyForm.title = undefined
      this.notifyForm.content = ''
      this.notifyDialogVisible = false
    },
    addNotify() {
      this.$refs['notifyForm'].validate(valid => {
        if (valid) {
          NotifyService.addNotify(this.notifyForm).then(() => {
            Notify.success(this, '发布成功!')
            this.initList()
            this.destroy()
          })
        }
      })
    },
    editNotify() {
      this.$refs['notifyForm'].validate(valid => {
        if (valid) {
          NotifyService.editNotify(this.notifyForm).then(() => {
            Notify.success(this, '编辑成功!')
            this.initList()
            this.destroy()
          })
        }
      })
    }
  }
}
</script>
